package com.chookss.home.workbench;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tiku.FeedbackActivity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class WorkFragment extends Fragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    SwipeMenuRecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvAll)
    TextView tvAll;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    @BindView(R.id.tvBottomNum)
    TextView tvBottomNum;
    @BindView(R.id.ivAllStatus)
    ImageView ivAllStatus;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    private WorkAdapter adapter;
    private List<WorkNewEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String type;//默认选择待审核1已审核
    private String startTime = "", endTime = "";
    private String employeeCodes = "", orgCodes = "";//筛选的组织和人
    private String isAdopt;//0未通过 1已通过不传查全部
    private boolean batchShow = false;//是否显示批量信息
    private int allNum = 0;//总数量
    private int workNum = 0;//选中的数量
    private boolean allSelect = false;//是否全选
    private List<WorkNewEntity> selectList = new ArrayList<>();
    private String workFlowType = "";

    public WorkFragment(String type) {
        this.type = type;
    }

    public WorkFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_works, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) srlView.getLayoutParams();
        params.setMargins(0, Utils.dip2px(mContext, 12), 0, 0);
        srlView.setLayoutParams(params);
        rvView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new WorkAdapter(R.layout.item_works, mContext, list,type,batchShow);

        if ("0".equals(type)) {
            tvNone.setText("暂无待审核工作");
        } else {
            tvNone.setText("暂无已审核工作");
        }
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        if ("0".equals(type)) {

            SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
                @Override
                public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                    int width = Utils.dip2px(mContext, 75);
                    int height = ViewGroup.LayoutParams.MATCH_PARENT;
                    // 注意：哪边不想要菜单，那么不要添加即可。
                    SwipeMenuItem addItem = new SwipeMenuItem(mContext)
                            .setBackground(R.color.main_color)
                            .setText("通过")
                            .setTextSize(15)
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
                    // 注意：哪边不想要菜单，那么不要添加即可。
                    SwipeMenuItem addItem2 = new SwipeMenuItem(mContext)
                            .setBackground(R.color.text_gray1)
                            .setText("不通过")
                            .setTextSize(15)
                            .setTextColor(Color.WHITE)
                            .setWidth(width)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItem2); // 添加菜单到右侧。
                }

            };
            rvView.setSwipeMenuCreator(mSwipeMenuCreator);
            SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
                @Override
                public void onItemClick(SwipeMenuBridge menuBridge) {
                    menuBridge.closeMenu();
                    int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
                    if (menuPosition == 0) {
                        passData(menuBridge.getAdapterPosition());
                    } else {
                        //未通过
                        Intent intent = new Intent(mContext, FeedbackActivity.class);
                        ArrayList<Map<String, String>> lists = new ArrayList<>();
                        Map<String, String> news = new HashMap<>();
                        news.put("id", list.get(menuBridge.getAdapterPosition()).getId());
                        news.put("projectCode", list.get(menuBridge.getAdapterPosition()).getProjectCode());
                        news.put("type", list.get(menuBridge.getAdapterPosition()).getWorkFlowType());
                        news.put("employeeCode", list.get(menuBridge.getAdapterPosition()).getAuditEmployeeCode());
                        lists.add(news);
                        intent.putExtra("myWorkBeans", (Serializable) lists);
                        intent.putExtra("type", 1);
                        startActivity(intent);
                    }
                }
            };
            rvView.setSwipeMenuItemClickListener(mMenuItemClickListener);
            rvView.setAdapter(adapter);
            srlView.autoRefresh();
        } else {
            rvView.setAdapter(adapter);
            getData();
        }
    }

    public void batchData() {
        if (tvAll == null) {
            return;
        }
        if (list.size() == 0) {
            MyToast.show("暂无待审核工作");
            return;
        }
        if (batchShow) {
            batchShow = false;
            tvAll.setVisibility(View.GONE);
            llBottom.setVisibility(View.GONE);
            adapter.notifyDataSetChanged();
        } else {
            batchShow = true;
            tvAll.setVisibility(View.VISIBLE);
            llBottom.setVisibility(View.VISIBLE);
            tvAll.setText("待审核(" + allNum + ")");
            tvBottomNum.setText("0条");
            adapter.notifyDataSetChanged();
        }
        adapter.setBatchShow(batchShow);
    }

    public void refreshData(String startTime, String endTime, String pass, List<ContactEntity> selectList) {
        this.startTime = startTime;
        this.endTime = endTime;
        this.isAdopt = pass;
        List<ContactEntity> selectLists = new ArrayList<>();
        selectLists.addAll(selectList);
        orgCodes = "";
        employeeCodes = "";
        for (int i = 0; i < selectLists.size(); i++) {
            if (!selectLists.get(i).isHalfSelect()) {
                if (selectLists.get(i).getType().equals("0")) {
                    if (Utils.isNull(orgCodes)) {
                        orgCodes = orgCodes + selectLists.get(i).getEmployeeCode();
                    } else {
                        orgCodes = orgCodes + "," + selectLists.get(i).getEmployeeCode();
                    }
                } else {
                    if (Utils.isNull(employeeCodes)) {
                        employeeCodes = employeeCodes + selectLists.get(i).getEmployeeCode();
                    } else {
                        employeeCodes = employeeCodes + "," + selectLists.get(i).getEmployeeCode();
                    }
                }
            }

        }
        isEnd = false;
        currentPage = 1;
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        if ("0".equals(type)) {
            //待审核 传0 已审核不传
            map.put("auditStatus", type);
        } else {
            //待审核不传 已审核传值，0未通过 1已通过 不传查全部
            if (!Utils.isNull(isAdopt)) {
                map.put("isAdopt", isAdopt);
            }
        }
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("employeeCodes", employeeCodes);
        map.put("orgCodes", orgCodes);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("type",workFlowType);// 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.selectKqMyWorkList, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                loadEnd();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (ivAllStatus == null) {
                            return;
                        }
                        if (currentPage == 1) {
                            list.clear();
                            allSelect = false;
                            ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                            setAllNum(true);
                            adapter.notifyDataSetChanged();
                        }
                        if (srlView == null || llNone == null) {
                            return;
                        }
                        int oldIndex = list.size();
                        list.addAll(XJson.getWorkNewEntityList(mContext, jsonObject.getString("data"), WorkNewEntity.class));
                        allNum = Utils.changeNumber(jsonObject.getString("total"));
                        if (srlView == null || llNone == null) {
                            return;
                        }
                        if ((list.size() - oldIndex) > 0) {
                            adapter.notifyItemRangeChanged(oldIndex, (list.size() - oldIndex));
                            srlView.setVisibility(View.VISIBLE);
                            llNone.setVisibility(View.GONE);
                        } else {
                            isEnd = true;
                            if (list.size() == 0) {
                                srlView.setVisibility(View.GONE);
                                llNone.setVisibility(View.VISIBLE);
                            }
                        }
                        if (allSelect) {
                            setAllNum(false);
                        } else {
                            setAllNum(true);
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
            }
        });
    }


    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    private void passData(int position) {
        Map<String, Object> map = new HashMap<>();
        //1审核通过 2审核未通过0未审核

        List<Map<String, String>> lists = new ArrayList<>();
        if (position >= 0) {
            //单个
            Map<String, String> news = new HashMap<>();
            news.put("auditStatus", "1");
            news.put("projectCode", list.get(position).getProjectCode());
            news.put("id", list.get(position).getId());
            news.put("type", list.get(position).getWorkFlowType());
            news.put("employeeCode", list.get(position).getAuditEmployeeCode());
            lists.add(news);
        } else {
            //批量
            for (int i = 0; i < selectList.size(); i++) {
                Map<String, String> news = new HashMap<>();
                news.put("auditStatus", "1");
                news.put("projectCode", selectList.get(i).getProjectCode());
                news.put("id", selectList.get(i).getId());
                news.put("type", selectList.get(i).getWorkFlowType());
                news.put("employeeCode", selectList.get(i).getAuditEmployeeCode());
                lists.add(news);
            }
        }

        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("审核成功");
                        EventBus.getDefault().post(new MyEvent("RefreshWork"));
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("操作失败，请稍后重试");
                }
            }
        });
    }

    @OnClick({R.id.llStatus, R.id.tvBottomNoPass, R.id.tvBottomPass})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llStatus:
                if (ivAllStatus == null) {
                    return;
                }
                if (allSelect) {
                    allSelect = false;
                    ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                    setAllNum(true);
                } else {
                    allSelect = true;
                    ivAllStatus.setBackgroundResource(R.drawable.icon_fx_select);
                    setAllNum(false);
                }
                adapter.notifyDataSetChanged();
                break;
            case R.id.tvBottomNoPass:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (selectList.size() == 0) {
                    MyToast.show("请先选择");
                } else {
                    Intent intent = new Intent(mContext, FeedbackActivity.class);
                    List<Map<String, String>> lists = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        Map<String, String> news = new HashMap<>();
                        news.put("id", selectList.get(i).getId());
                        news.put("projectCode", selectList.get(i).getProjectCode());
                        news.put("type", selectList.get(i).getWorkFlowType());
                        news.put("employeeCode", selectList.get(i).getAuditEmployeeCode());
                        lists.add(news);
                    }
                    intent.putExtra("myWorkBeans", (Serializable) lists);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }
                break;
            case R.id.tvBottomPass:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (selectList.size() == 0) {
                    MyToast.show("请先选择");
                } else {
                    passData(-1);
                }
                break;
        }
    }

    private void setAllNum(boolean isZero) {
        workNum = 0;
        selectList.clear();
        if (tvBottomNum == null) {
            return;
        }
        if (allSelect) {
            for (int i = 0; i < list.size(); i++) {
                workNum = workNum + 1;
                list.get(i).setSelect(true);
            }
            selectList.addAll(list);
        } else {
            for (int i = 0; i < list.size(); i++) {
                if (isZero) {
                    list.get(i).setSelect(false);
                } else {
                    if (list.get(i).isSelect()) {
                        selectList.add(list.get(i));
                        workNum = workNum + 1;
                    }
                }
            }
        }
        if ((workNum == allNum || workNum == list.size()) && workNum != 0) {
            allSelect = true;
            ivAllStatus.setBackgroundResource(R.drawable.icon_fx_select);
        } else {
            allSelect = false;
            ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
        }
        tvBottomNum.setText(workNum + "条");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("RefreshWork_Select")){
                if(map.get("RefreshWork_Select").equals("false")){
                    allSelect = false;
                    ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                }
                setAllNum(false);
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshWork".equals(msg)) {
                if (tvAll == null) {
                    return;
                }
                allSelect = false;
                ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                setAllNum(true);
                batchShow = false;
                adapter.setBatchShow(batchShow);
                tvAll.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                currentPage = 1;
                isEnd = false;
                getData();
            } else if ("RefreshWork_Video".equals(msg)) {
                if ("0".equals(type)) {
                    if (tvAll == null) {
                        return;
                    }
                    batchShow = false;
                    adapter.setBatchShow(batchShow);
                    tvAll.setVisibility(View.GONE);
                    llBottom.setVisibility(View.GONE);
                    currentPage = 1;
                    isEnd = false;
                    getData();
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();

    }

}
